import React from 'react';
import ReactDOM from 'react-dom';

var SetIntervalMixin = {
	componentWillMount:function(){
		this.intervals=[]
	},
	setInterval:function(){
		this.intervals.push(setInterval.apply(null,arguments));
	},
	componentWillUnmount:function(){
		this.intervals.map(clearInterval)
	}
};

var CartTimeoutMixin = {
	componentWillMount:function(){
		this.setInterval(this.descrementCartTimer,1000)
	},
	descrementCartTimer:function(){
		if(this.state.cartTimeout==0){
			this.props.alertCartTimeout();
			return ;
		}
		this.setState({cartTimeout:this.state.cartTimeout-1})
	}
}

class BookList extends React.Component {
	constructor (props){
		super(props)
		this.state={
			books:[],
			selectBooks:[],
			error:false
		}
		//this.componentWillMount=this.componentWillMount.bind(this)
		this.handlerSelectBooks =this.handlerSelectBooks.bind(this);
		this.handlerSubmit = this.handlerSubmit.bind(this);


	}
	componentWillMount(){
		$.get('/api/book',function(result){
			this.setState({books:result})
		}.bind(this))
	}

	_renderBook(book,index){
		return (
			<div key={index} className="form-group">
			<div className="checkbox">
				<label>
					<input onChange={this.handlerSelectBooks}    type="checkbox" value={book.name}/>
					{book.name}--{book.author}
				</label>
			</div>
		</div>)
	}

	_renderError(){
		if(this.state.error){
			return(<div className="alert alert-danger">
				<button type="button" className="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				<strong>Title!</strong> Alert body ...{this.state.error}
			</div>)
		}
	}
	render(){
		var errorMessage = this._renderError()

		return (<div><h3>Choose from wide variety of books available in our store. </h3>
				{errorMessage}
				<form onSubmit={this.handlerSubmit} role="form">
					<legend>Select Books </legend>
				
					 {this.state.books.map((book,index) => {
						return this._renderBook(book,index); })
						}
				
					<button type="submit" className="btn btn-success">Submit</button>
				</form>
			</div>)
	}
	handlerSubmit(event){

		event.preventDefault();
		console.log(event);
		if(this.state.selectBooks.length ===0){
			this.setState({error:"Please choose at least on book to continue."})
		}
		else{
			this.setState({error:false});
			this.props.updateFormData({selectBooks:this.state.selectBooks});
		}


	}
	handlerSelectBooks(event){
		var selectBooks = this.state.selectBooks;
		var index = selectBooks.indexOf(event.target.value);
		if(index === -1){
			selectBooks.push(event.target.value);
		}
		else {
			selectBooks.splice(index,1);
		}
		this.setState({selectBooks:selectBooks});

		console.log('handlerSelectBooks')
	}
}

class Success extends React.Component {
	render(){
		var numberOfDays = "1 to 2";
		if(this.props.data.deliveryOption==="Normal"){
			numberOfDays = "3 to 4";
		}
		return (
				<div>
					<h2>Thank for you shopping with us {this.props.data.deliveryOption}</h2>
					<h4>
						You will soon get {this.props.data.selectBooks.join(', ')} at 
						{this.props.data.shippingAddress} in approximately 
					</h4>
				</div>
			)
	}
}

class ShippingDetails extends React.Component {

	constructor(props){
		super(props);
		this.state={ fullName: '', contactNumber: '', shippingAddress: '', error:false };
		this.handlerSubmit = this.handlerSubmit.bind(this);
		this.handlerChange = this.handlerChange.bind(this);
		this.goBack=this.goBack.bind(this);
	}
	_renderError() {
		if (this.state.error) {
		return (
		<div className="alert alert-danger">
		{this.state.error}
		</div>
		);}
	}
	_validateInput(){
		if (this.state.fullName === '') {
				this.setState({error: "Please enter full name"});
			} else if (this.state.contactNumber === '') {
				this.setState({error: "Please enter contact number"});
			} else if (this.state.shippingAddress === '') {
				this.setState({error: "Please enter shipping address"});
			} else {
				this.setState({error: false});
			return true;
		}
	}
	handlerSubmit(event){
		event.preventDefault();
		var formData ={
			fullName: this.state.fullName,
			contactNumber: this.state.contactNumber,
			shippingAddress: this.state.shippingAddress
		}
		if (this._validateInput()) {
			this.props.updateFormData(formData);
		}
	}
	handlerChange(event,attribute){
		var newState = this.state;
		newState[attribute]= event.target.value;
		this.setState(newState);
		console.log(this.state);
	}
	goBack(){
		this.props.gotoPreStep();
	}


	render(){
		var errorMessage =this._renderError();
		return (<div><form onSubmit={this.handlerSubmit} role="form">
			<legend>ShippingDetails</legend>
			{errorMessage}
		
			<div className="form-group">
				<label for="">fullName</label>
				<input type="text" className="form-control" onChange={(event)=>this.handlerChange(event,'fullName')}   placeholder="fullName"/>
			</div>
			<div className="form-group">
				<label for="">contactNumber</label>
				<input type="text" className="form-control" onChange={(event)=>this.handlerChange(event,'contactNumber')}   placeholder="contactNumber"/>
			</div>
			<div className="form-group">
				<label for="">shippingAddress</label>
				<input type="text" className="form-control" onChange={(event)=>this.handlerChange(event,'shippingAddress')}   placeholder="shippingAddress"/>
			</div>
			<button type="submit" className="btn btn-primary">Submit</button>
			<button type="button" onClick={this.goBack} className="btn btn-warring">Go Back</button>
		</form></div>)
	}
}

class DeliveryDetails extends React.Component {
	constructor(props){
		super(props);
		this.state={deliveryOption:'Primary',cartTimeout:this.props.cartTimeout}
		this.handlerChange=this.handlerChange.bind(this);
		this.handlerSubmit=this.handlerSubmit.bind(this);
		this.goBack=this.goBack.bind(this);

	}
	handlerSubmit(event){
		event.preventDefault();
		this.props.updateFormData({deliveryOption:this.state.deliveryOption});

	}
	handlerChange(event){
		this.setState({deliveryOption:event.target.value});
	}
	goBack(){

		this.props.gotoPreStep();
	}

	render(){
		var minutes = Math.floor(this.state.cartTimeout / 60);
		var seconds = this.state.cartTimeout - minutes * 60;
		return (<div><form onSubmit ={this.handlerSubmit} role="form">
			<legend>DeliveryDetails </legend>
			
			<div className="radio">
				<label>
					<input type="radio" onChange={this.handlerChange}  
					value="Primary" checked={this.state.deliveryOption=='Primary'}/>
					 Primary
				</label>
			</div>
			<div className="radio">
				<label>
					<input type="radio" checked={this.state.deliveryOption=='Normal'}  value="Normal" onChange={this.handlerChange} />
					 Normal
				</label>
			</div> 
			<button type="submit" className="btn btn-primary">Submit</button>
			<button type="button" onClick={this.goBack} className="btn btn-warring">Go Back</button>
		</form>
		<div className='well'>
			<span className="glyphicon glyphicon-time" aria-hidden="true"></span>
			You have {minutes} Minutes , {senconds} Seconds ,before confirming order. 
		</div>
		</div>)
	}
}

class Confirmation extends React.Component {

	constructor(props){
		super(props)
		this.handlerSubmit=this.handlerSubmit.bind(this);
		this.goBack=this.goBack.bind(this);
	}
	handlerSubmit(event){
		event.preventDefault();
		this.props.updateFormData();

	}
	goBack(){

		this.props.gotoPreStep();
	}
	render(){
		console.log(this.props.data);
		return(<div><h1>are you sure you want to submit the data?</h1>
			<form onSubmit={this.handlerSubmit} role="form">
				<legend>Confirm?</legend>
			
				<div className="form-group">
					<label for="">fullName</label>
					<input type="text" className="form-control" value={this.props.data.fullName} readOnly/>
				</div>
				<div className="form-group">
					<label for="">contactNumber</label>
					<input type="text" className="form-control" value={this.props.data.contactNumber} readOnly/>
				</div>
				<div className="form-group">
					<label for="">shippingAddress</label>
					<input type="text" className="form-control" value={this.props.data.shippingAddress} readOnly/>
				</div>
				<div className="form-group">
					<label for="">Selected books</label>
					<input type="text" className="form-control" value={this.props.data.selectBooks.join(", ")} readOnly/>
				</div>
			
				<button type="submit" className="btn btn-primary">Submit</button>
				<button type="button" onClick={this.goBack} className="btn btn-warring">Go Back</button>
			</form>
			</div>)
	}
}


class BookStore extends React.Component {
	constructor (props){
		super(props)
		this.state={
			currentStep:1,
			formValues:{},
			cartTimeout:60*15
			 
		}
		this.updateFormData = this.updateFormData.bind(this);
		this.gotoPreStep=this.gotoPreStep.bind(this);
		this.updateCartTimeout = this.updateCartTimeout.bind(this);
		this.alertCartTimeout = this.alertCartTimeout.bind(this);

	}
	alertCartTimeout(){
		React.render(<ModalAlertTimeout />, document.getElementById('modalAlertTimeout'));
		this.setState({currentStep: 1, formValues: {}, cartTimeout: 1});

	}

	updateCartTimeout(timeout){
		this.setState({cartTimeout:timeout});
	}
	updateFormData(formDatas){
		console.log('updateFormData');
		console.log(formDatas);
		var formValues = Object.assign({},this.state.formValues,formDatas);
		var nextStep = this.state.currentStep + 1;
		console.log(formValues);
		this.setState({formValues:formValues,currentStep:nextStep})
	}
	gotoPreStep(){
		var preStep=this.state.currentStep-1;
		var formValues = Object.assign({},this.state.formValues,this.state.formValues);
		console.log(formValues);
		this.setState({currentStep:preStep,formValues:formValues});
	}
	
	render(){
		switch(this.state.currentStep){
			case 1:
				return <BookList updateFormData={this.updateFormData} />
			case 2:
				return <ShippingDetails  cartTimeout={this.state.cartTimeout}
				 gotoPreStep={this.gotoPreStep} updateCartTimeout={this.updateCartTimeout} updateFormData={this.updateFormData} />
				
			case 3:
				return <DeliveryDetails updateCartTimeout={this.updateCartTimeout} cartTimeout={this.state.cartTimeout} updateFormData={this.updateFormData} gotoPreStep={this.gotoPreStep} />
			case 4:
				return <Confirmation updateFormData={this.updateFormData}  gotoPreStep={this.gotoPreStep} data={this.state.formValues} />
			case 5:
				return <Success data={this.state.formValues} />
			default:
				return <BookList updateFormData={this.updateFormData} />

		}
	}
}

export default BookStore